package com.wzy.netty.core.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * 描述
 * 创建人    Wzy
 * 创建时间: 2020-05-23  1:10
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
//        byte[] bytes = new byte[msg.readableBytes()];
//        msg.readBytes(bytes);
//        //将buffer转换成字符串
//        String message = new String(bytes, CharsetUtil.UTF_8);
//        System.out.println("服务器接收到的消息:" + message);
//        System.out.println("服务端接收到消息量=" + (++this.count));
//
//        //服务器会送数据给客户端,会送一个随机id
//        ByteBuf buf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8);
//
//        ctx.writeAndFlush(buf);
//    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务端接收到信息如下: 长度=" + len + "内容" + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务器接收到消息包数量:" + (++this.count));
        //回复消息
        String responseContent = UUID.randomUUID().toString();
        byte[] bytes = responseContent.getBytes(CharsetUtil.UTF_8);
        int length = responseContent.getBytes(CharsetUtil.UTF_8).length;
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setContent(bytes);
        messageProtocol.setLen(length);
        ctx.writeAndFlush(messageProtocol);
    }
}
